/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.primefaces.optimus.el;

import java.beans.FeatureDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.el.ELContext;
import javax.el.ELResolver;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import com.google.inject.Injector;

import org.primefaces.optimus.config.BeanInfo;
import org.primefaces.optimus.config.OptimusBeanContext;
import org.primefaces.optimus.config.Scope;
import org.primefaces.optimus.config.annotations.OnInit;
import org.primefaces.optimus.util.Constants;
import org.primefaces.optimus.util.OptimusBeanContextUtils;

public class OptimusELResolver extends ELResolver {
	
	private final static Logger logger = Logger.getLogger(OptimusELResolver.class.getName());

	@Override
	public Class<?> getCommonPropertyType(ELContext elContext, Object base) {
        if (base != null) 
        	return null;
        
        return Object.class;
	}

	@Override
	public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext elContext, Object base) {
		return null;
	}

	@Override
	public Class<?> getType(ELContext elContext, Object base, Object property) {
		if(base != null)
			return null;
		
		BeanInfo beanInfo = OptimusBeanContextUtils.getBeanContext().getBeanInfo((String) property);
		
		if(beanInfo != null) {
			elContext.setPropertyResolved(true);
			return beanInfo.getClazz();
		}
		
		return null;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Object getValue(ELContext elContext, Object base, Object property) {
		if(base != null)
			return null;
		
		OptimusBeanContext beanContext = OptimusBeanContextUtils.getBeanContext();
		if(beanContext == null)
			return null;
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		BeanInfo beanInfo = beanContext.getBeanInfo((String) property);
		
		if(beanInfo != null) {
			elContext.setPropertyResolved(true);
			Scope scope = beanInfo.getScope();
			
			switch (scope) {
				case REQUEST:
					return retrieveBean(externalContext.getRequestMap(), beanInfo);
	
				case VIEW:
					Map<String,Object> viewScopeMap = (Map<String, Object>) externalContext.getSessionMap().get(Constants.VIEW_SCOPE_KEY);
					return retrieveBean(viewScopeMap, beanInfo);
					
				case SESSION:
					return retrieveBean(externalContext.getSessionMap(), beanInfo);
				
				case APPLICATION:
					return retrieveBean(externalContext.getApplicationMap(), beanInfo);
			}
		}

		return null;
	}
	
	private Object retrieveBean(Map<String,Object> map, BeanInfo beanInfo) {
		Object bean = null;
		
		if(map.get(beanInfo.getName()) != null) {
			bean =  map.get(beanInfo.getName());
		} else {
			bean = getInjector().getInstance(beanInfo.getClazz());
			map.put(beanInfo.getName(), bean);
			
			invokeMethodAnnotatedWith(bean, OnInit.class);
		}
		
		return bean;
	}
	
	private void invokeMethodAnnotatedWith(Object obj, Class<? extends Annotation> annot) {
		for(Method method : obj.getClass().getMethods()) {
			if(method.getAnnotation(annot) != null)
				try {
					method.invoke(obj, null);
					
					break;
				} catch (Exception e) {
					logger.severe(e.getMessage());
				}
		}
	}

	@Override
	public boolean isReadOnly(ELContext elContext, Object base, Object property) {
		return false;
	}

	@Override
	public void setValue(ELContext elContext, Object base, Object value, Object property) {
		if(base != null)
			return;
	}
	
	private Injector getInjector() {
		return (Injector) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(Constants.INJECTOR_KEY);
	}
}